package com.controller;


import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.contants.ResultContants;
import com.contants.SessionKeys;
import com.entity.SysUser;
import com.service.UserService;
import com.utils.ImgCode;
import com.utils.JsonResult;
import com.utils.MD5;

/*拦截器验证无登录信息时，跳转登录页面*/
@Controller
//@RequestMapping("/")
public class LoginController {
	@RequestMapping("/loginForm")
	public String getLongin(){
		System.err.println("进入登录页");
		return "/login";
	}
	
	/*登录页面的获取验证码方法*/
	@RequestMapping("/getCode")
	public void getCode(HttpServletRequest request, HttpServletResponse response){
		ImgCode imgCode=new ImgCode();
		imgCode.getRandcode(request, response);
	}
	@Autowired
	private UserService userservice;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
//	输入用户名，ajax验证是否存在
	@PostMapping("/validate")
	@ResponseBody
	public JsonResult validate(HttpServletRequest request,HttpServletResponse response) throws IOException{
		JsonResult result=new JsonResult();
		String name = request.getParameter("name");
		if (name==null||name=="") {
			result.setCode(ResultContants.failCode);
        	result.setMessage("用户名不存在！");
        	return result;
		}
		SysUser loginUser=new SysUser();
		loginUser.setUserName(name);
//		name =new String(name.getBytes("ISO-8859-1"), "UTF-8");
		//javascript传值编码异常，上述方法编码更正
		SysUser dbUser = userservice.queryUserByUserName(loginUser);
		if(dbUser!=null){
			result.setCode(ResultContants.successCode);
			result.setMessage("可以登录了");
		}else{
			result.setCode(ResultContants.failCode);
			result.setMessage("用户名不正确");
		}
		return result;	
	}
	
	/*点击登录后，验证登录信息*/
	@RequestMapping("/login")
	@ResponseBody  //响应数据为json数据
	public JsonResult  login(SysUser loginUser,HttpServletRequest request,HttpServletResponse response){
		JsonResult result = new JsonResult();
//		1、判定验证码是否有效
//		2、根据用户名查询数据库，看用户是否有效
//		3、对请求的密码加密，再和密文比对
//		4、读取用户的权限信息，并写入redis, key放进session
        	if(loginUser.getUserName()!=""){
        		SysUser dbUser = userservice.queryUserByUserName(loginUser);
        		MD5 md5 = new MD5();
        		String md5ofStr = md5.getMD5ofStr(loginUser.getPassword());
        		if(md5ofStr.equals(dbUser.getPassword())){//登录成功
        			/*登陆成功，获取ip，存数据库，防止多处登陆*/
        			String ip = LoginController.getLinuxLocalIp();
        			dbUser.setPassword(ip);
        			
//        			把用户信息写入session中（注意：必须对用户信息脱密）
        			dbUser.setPassword(null);
        			 //获取uuid
        	        String uuid =UUID.randomUUID().toString().replace("-", "");
        	        //创建cookie
        	        Cookie cookie = new Cookie("userCookie", uuid);
        	        response.addCookie(cookie);
        	        String userJson = JSONArray.toJSON(dbUser).toString();
        	        //把用户信息存入redis  set（key，value，过期时长，过期格式） 设置三分钟
        	        stringRedisTemplate.opsForValue().set("user:" + uuid, userJson, 3, TimeUnit.MINUTES);
        	    	HttpSession session = request.getSession(true);
					session.setAttribute(SessionKeys.SYS_USER, dbUser);
					// 单独写入用户名到session中，便于后期使用
					session.setAttribute(SessionKeys.SYS_USER_NAME, dbUser.getUserName());
					session.setAttribute(SessionKeys.REDIS_KEY, "user" + ":" + uuid);
        			result.setCode(ResultContants.successCode);
        			result.setMessage("登录成功！");
        		}else{
        			result.setCode(ResultContants.failCode);
                	result.setMessage("密码不匹配！请重新登录。。。。");
        		}
        	}else{
        		result.setCode(ResultContants.failCode);
            	result.setMessage("用户不存在！");
        	}
		return result;
	}

	
	/*登陆成功获取本机ip，存入数据库，退出或关闭就清除数据库信息，实现单地点登陆*/
	
	
	public static String getLinuxLocalIp() {
		String ip = "";
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				String name = intf.getName();
				if (!name.contains("docker") && !name.contains("lo")) {
					// 不含有docker和lo
					for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
						InetAddress inAddress = enumIpAddr.nextElement();
						if (!inAddress.isLoopbackAddress()) {
							String ipaddress = inAddress.getHostAddress().toString();
							if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
									&& !ipaddress.contains("fe80")) {
								ip = ipaddress;
							}
						}
					}
				}
			}
		} catch (SocketException e) {
			System.out.println("获取ip失败");
			ip = "127.0.0.1";
		}
		return ip;
	}
	
	
	@RequestMapping("/loginOut")
	@ResponseBody
	public JsonResult loginOut(HttpServletRequest request,HttpServletResponse response){
	/*	先从session取出rediskey，然后删除redis*/
		 JsonResult jsonResult = new JsonResult();
		 jsonResult.setCode(ResultContants.failCode);
	    HttpSession session = request.getSession(true); 
	    String sessionKey = (String) session.getAttribute(SessionKeys.REDIS_KEY);
	    if (sessionKey!=null) {
	    	Boolean delete = stringRedisTemplate.delete(sessionKey);
	    	if (delete) {
	    		System.out.println("退出登录了");
	    		 jsonResult.setCode(ResultContants.successCode);
			}
		}
	    /*清除session*/
		session.invalidate();
	    /*清除cookie*/
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equalsIgnoreCase("userCookie")) {
					cookie.setMaxAge(0);
					cookie.setPath("/");
					response.addCookie(cookie);
				}
			}
		}
		return jsonResult;
	}
	
	
	@RequestMapping("/index")
	public String getIndex(HttpServletRequest request,Model model){
		HttpSession session = request.getSession();
		Object attribute = session.getAttribute(SessionKeys.SYS_USER_NAME);
		model.addAttribute("username", attribute);
		return "upload.html";
	}
	
	
	@RequestMapping("/toMainPage")
	@ResponseBody
    public JsonResult toMainPage(HttpServletRequest request, HttpServletResponse response) {
        JsonResult jsonResult = new JsonResult();
        String userJson="";
		HttpSession session=request.getSession(true);
		Object redisKey =session.getAttribute(SessionKeys.REDIS_KEY);
		if (redisKey!=null) {
			 userJson = stringRedisTemplate.opsForValue().get(redisKey);
		}
		jsonResult.setInfo(userJson);
		jsonResult.setCode(ResultContants.successCode);
		return jsonResult;
    }
}
